﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
/// <summary>
/// Author: toanvt
/// CreatedDate: 12/12/2011
/// Description: Danh sách Khách Hàng, Đối tác
/// </summary>
public partial class Administrator_AdminCustomers : System.Web.UI.Page
{
    private Int32 pageIndex = 1;
    private Int32 pageSize = 10;
    private Int32 totalRecord;
    private Int32 nhomKhachHangID = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
        }
        catch (Exception)
        {
            pageIndex = 1;
        }

        try
        {
            nhomKhachHangID = Int32.Parse(Request.QueryString["NhomKhachHangID"].ToString()); 
        }
        catch
        {
            nhomKhachHangID = -1;
        }

        pageSize = this.PaggingControl1.PageSize;

        if (!Page.IsPostBack)
        {
            LoadDataCustomer(nhomKhachHangID);
        }
    }

    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: lấy toàn bộ danh sách Khách hang, Đối tác
    /// </summary>
    private void LoadDataCustomer(Int32 nhomKhachHangID)
    {
        // Khởi tạo thực thể và gán các giá trị lọc
        KhachHang theKhachHang = new KhachHang();
        theKhachHang.KhachHangID = HangSo.DEFAULT_ID;
        theKhachHang.TenKhachHangVN = "";
        theKhachHang.TenKhachHangOther = "";
        theKhachHang.DienThoai = "";
        theKhachHang.Email = "";
        theKhachHang.NhomKhachHang = nhomKhachHangID;
        DataSet dsCustomers = KhachHangProvider.GetKhachHangsByFillter(theKhachHang, pageIndex, pageSize, out totalRecord);

        if (dsCustomers.Tables[0].Rows.Count > 0)
        {
            rpCustomers.DataSource = dsCustomers;
            rpCustomers.DataBind();
            foreach (RepeaterItem item in rpCustomers.Items)
            {
                CheckBox ckPublish = (CheckBox)item.FindControl("ckPublish");
                if (ckPublish.Checked == true)
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/btncheck.png";
                }
                else
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/unpublish.jpg";
                }
            }
        }

        this.PaggingControl1.PageIndex = pageIndex;
        this.PaggingControl1.TotalRecord = totalRecord;
        this.PaggingControl1.PageURL = "AdminCustomers.aspx?NhomKhachHangID=" + nhomKhachHangID.ToString();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminCustomerIU.aspx?NhomKhachHangID=" + nhomKhachHangID.ToString());
    }

    protected void rpCustomers_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        String cmdName = e.CommandName;
        Int32 maKH=-1;
        try
        {
            maKH = Int32.Parse(e.CommandArgument.ToString());
        }
        catch(Exception ex)
        {
 
        }

        if (cmdName.ToLower() == "delete1")
        {
            KhachHangProvider.DeleteKhachHangByKhachHangID(maKH);
            LoadDataCustomer(nhomKhachHangID);
        }

        else if (cmdName == "change_number_of_order")
        {

            try
            {
                Int32 numberOfOrder = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                KhachHangProvider.UpdateNumberOfOrderByKhachHangId(maKH,numberOfOrder);
            }
            catch (Exception)
            { }
            LoadDataCustomer(nhomKhachHangID);
        }

        else if (cmdName == "publish")
        {
            KhachHangProvider.ChangePublishByDanhMucKhachHangID(maKH);
            LoadDataCustomer(nhomKhachHangID);
        }
        else if (cmdName == "save_all")
        {
            foreach (RepeaterItem item in rpCustomers.Items)
            {
               
                Int32 numberOfOrder = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                maKH = Int32.Parse(((Literal)item.FindControl("ltrKhachHangID")).Text.Trim());
                KhachHangProvider.UpdateNumberOfOrderByKhachHangId(maKH,numberOfOrder);
            }
            LoadDataCustomer(nhomKhachHangID);
        }
    }

    protected void rpCustomers_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Image imgHinhAnh = (Image)e.Item.FindControl("imgHinhAnhUrl");
        Label lbHinhAnh = (Label)e.Item.FindControl("lbHinhAnhUrl");
        if (lbHinhAnh != null)
        {
            if (string.IsNullOrEmpty(lbHinhAnh.Text) == false)
            {
                if ((RemoteFileExists(@"~\ImageDatas\Customers\" + lbHinhAnh.Text)) == false)
                {
                    imgHinhAnh.ImageUrl = @"~\ImageDatas\Customers\" + lbHinhAnh.Text;
                }
                else
                {
                    imgHinhAnh.ImageUrl = @"~\ImageDatas\Customers\noImage.gif";
                }
            }
            else
            {
                imgHinhAnh.ImageUrl = @"~\ImageDatas\Customers\noImage.gif";
            }
        }
    }

    /// <summary>
    ///Author: toanvt
    ///CreatedDate: 12/12/2011
    ///Description: Kiểm tra sự tồn tại của file Ảnh quan Url
    /// </summary>
    /// <param name="url">Url trỏ đến file ảnh</param>
    /// <returns>Trạng thái có hay chưa</returns>
    private bool RemoteFileExists(string url)
    {
        bool result = false;
        using (System.Net.WebClient client = new WebClient())
        {
            try
            {
                Stream stream = client.OpenRead(url);
                if (stream != null)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch
            {
                result = false;
            }
        }
        return result;
    }
}
